import java.util.LinkedList;
import java.util.Queue;

/**
 * @ClassName Offer13
 * @Description 剑指 Offer 13. 机器人的运动范围
 * @Author clockTown
 * @Date 2021/8/28 8:36
 * @Version 1.0
 */
class Offer13 {
}

/**
 * DFS
 */
class Offer13V0 {
    private int m;
    private int n;
    private boolean[][] visited;

    public int movingCount(int m, int n, int k) {
        this.m = m;
        this.n = n;
        this.visited = new boolean[m][n];
        return dfs(0, 0, k);
    }

    private int dfs(int i, int j, int k) {
        //临界条件判断：超出边界，已被访问过，数位和大于k
        if (i >= m || j >= n || visited[i][j] || sum(i, j) > k){
            return 0;
        }
        visited[i][j] = true;
        //向右和向下移动一格
        return 1 + dfs(i + 1, j, k) + dfs(i, j + 1, k);

    }

    private int sum(int x, int y) {
        int sum = 0;
        while (x != 0) {
            sum += x % 10;
            x /= 10;
        }
        while (y != 0){
            sum += y %10;
            y /= 10;
        }
        return sum;
    }

}

/**
 * BFS
 */
class Offer13V1 {
    public int movingCount(int m, int n, int k) {
        boolean[][] visited = new boolean[m][n];
        int res = 0;
        Queue<int[]> queue= new LinkedList<int[]>();
        queue.add(new int[] { 0, 0, 0, 0 });
        while(queue.size() > 0) {
            int[] x = queue.poll();
            int i = x[0], j = x[1], si = x[2], sj = x[3];
            if(i >= m || j >= n || k < si + sj || visited[i][j]) {
                continue;
            }
            visited[i][j] = true;
            res ++;
            queue.add(new int[] { i + 1, j, (i + 1) % 10 != 0 ? si + 1 : si - 8, sj });
            queue.add(new int[] { i, j + 1, si, (j + 1) % 10 != 0 ? sj + 1 : sj - 8 });
        }
        return res;
    }
}